/* eslint-disable react-hooks/exhaustive-deps */
// 我是约定@umijs/plugin-model写法、可以写很多全局状态管理
import React, { useState, useCallback, useMemo } from 'react';
import Loading from '@/components/Exception/Loading';
import { getDictionaryConfig } from '@/services';

interface DictionariesItem {
  label: string;
  value: string;
}

interface GlobalModelType {
  dictionaries?: Record<
    /**
    /* 字典类型：role:角色,sex:性别 
    */
    string | number,
    DictionariesItem[]
  >;
}

export declare type useGlobalModelType = {
  /**
   * 未加载完成的loading显示
   */
  loading: React.ReactNode;
  /**
   * 全局信息
   */
  globalInfo: GlobalModelType | undefined;
  /**
   * 获取全局指定key 的数据
   */
  getGlobalInfo: (field: any) => any;
  /**
   * 设置全局字典
   * @dictionaries
   */
  setGlobalDictionaries: (dictionaries: any) => void;
  // /**
  //  * 刷新字段
  //  * @dictionaries
  //  */
  // refreshGlobalDictionaries: (type: string) => void;
  /**
   * 请求字段数据
   * @dictionaries
   */
  requestDictionaries: () => void;
};

export default function useGlobalModel(): useGlobalModelType {
  const [globalInfo, setGlobalInfo] = useState<GlobalModelType>();

  //设置字典
  const setGlobalDictionaries = useCallback((dictionaries: any) => {
    return setGlobalInfo({
      ...globalInfo,
      dictionaries,
    });
  }, []);

  // 请求字典数据
  const requestDictionaries = useCallback(() => {
    getDictionaryConfig()
      .then((res: any) => {
        setGlobalDictionaries(res.data);
      })
      .catch((err: any) => {
        console.log(err);
      });
  }, []);

  const getGlobalInfo = (field: string) => {
    if (!field) {
      return globalInfo;
    }
    // @ts-ignore
    return globalInfo[field];
  };

  // const refreshGlobalDictionaries = (type: string) => {
  //   getDictionaryByType({
  //     type,
  //   })
  //     .then((res: any) => {
  //       const dconfig: any = [];
  //       res.data.list?.forEach((i: API.zidianxuanxiang) => {
  //         dconfig.push({
  //           label: i.value,
  //           value: i.id,
  //         });
  //       });
  //       const dictionaries = { ...globalInfo?.dictionaries };
  //       dictionaries[type] = dconfig;
  //       setGlobalDictionaries(dictionaries);
  //     })
  //     .catch(() => {});
  // };

  const loading = useMemo(() => React.createElement(Loading), []);

  return {
    loading,
    globalInfo,
    getGlobalInfo,
    setGlobalDictionaries,
    requestDictionaries,
    // refreshGlobalDictionaries
  };
}
